﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Deployment.Application;
using CCF20Model;
using Microsoft.Win32;

namespace CCF20Model.ConfigurationFile
{

    public class ConfiguraitonHelper
    {
        internal static string _configFilePath;
        internal static AppConfig _ccfConfig = new AppConfig("车务通无忧驾驶系统.exe.config");
        internal static AppConfig _zicConfig = new AppConfig("ZICMonitor.exe.config");
        public static WiseLinkConfiguration _myConfiguration;  
        public static WiseLinkConfiguration MyConfiguration  
        { get
            {
              if (_myConfiguration == null)   
              {
                  DeSerializeToObject();
              }
                return _myConfiguration;
            }

        }

        internal static Dictionary<Tuple<AppConfigFileName, string>, AppConfigFileNode> ConfigFileNodeList = new Dictionary<Tuple<AppConfigFileName, string>, AppConfigFileNode>
        {
            { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.CCF, AppConfigFileNodeName.CCF20Entities), 
                new AppConfigFileNode { SectionName ="connectionStrings",NodeName ="CCF20Entities", AttributeName = "connectionString"}
            },

            { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.CCF, AppConfigFileNodeName.AspnetMembershipConnectionString),
                new AppConfigFileNode { SectionName ="connectionStrings",NodeName ="AspnetMembershipConnectionString", AttributeName = "connectionString"}
             },
             { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.CCF, AppConfigFileNodeName.CCF20Log),
                new AppConfigFileNode { SectionName ="listeners",NodeName ="CCF20Log", AttributeName = "fileName"}
             },
            {
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.ZICMonitor, AppConfigFileNodeName.CCF20Entities), 
                new AppConfigFileNode { SectionName ="connectionStrings",NodeName ="CCF20Entities", AttributeName = "connectionString"}
             },
             { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.ZICMonitor, AppConfigFileNodeName.CCF20Log),
                new AppConfigFileNode { SectionName ="listeners",NodeName ="CCF20Log", AttributeName = "fileName"}
             },
             { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.ZICMonitor, AppConfigFileNodeName.ZICDebug),
                new AppConfigFileNode { SectionName ="listeners",NodeName ="ZICDebug", AttributeName = "fileName"}
             },
             { 
                Tuple.Create<AppConfigFileName,string>(AppConfigFileName.ZICMonitor, AppConfigFileNodeName.ZICMonitor),
                new AppConfigFileNode { SectionName ="listeners",NodeName ="ZICMonitor", AttributeName = "fileName"}
             },
        };
        static ConfiguraitonHelper()
        {
            try
            {
                _configFilePath = ApplicationDeployment.CurrentDeployment.DataDirectory;
                LoggerHelper.LogCCF20("IsNetworkDeployed");
            }
            catch
            {
                _configFilePath = ".";
                LoggerHelper.LogCCF20("IsLocalDeployed");
            }

            _configFilePath += "\\CCFConfiguration.xml";

            RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\WiseLink", true);

            if (!File.Exists(_configFilePath))
            {
                _configFilePath = reg.GetValue("ConfigurationPath").ToString();
            }
            if (!File.Exists(_configFilePath))
            {
                throw new ArgumentException("Can't find the config file path after checking 1. network deploy, 2.local path 3. registry key");
            }
            
            if (reg == null)
            {
                reg = Registry.CurrentUser.CreateSubKey("SOFTWARE\\WiseLink", RegistryKeyPermissionCheck.ReadWriteSubTree);
                LoggerHelper.LogCCF20("Create Registry Key for WiseLink");
            }
            reg.SetValue("ConfigurationPath", _configFilePath);
            LoggerHelper.LogCCF20(string.Format(" 找到配置文件路径:{0}", _configFilePath));
           
        }
        public static void UpdateRegistry()
        {
            DeSerializeToObject();
            RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\WiseLink", true);
            reg.SetValue("ZICUrl", MyConfiguration.zicurl);
            reg.SetValue("CustomerType", MyConfiguration.customertype);
            reg.SetValue("English", MyConfiguration.isenglish);
        }
        public static void SerializeToXml()
        {
            SerializeToXml(MyConfiguration);
        }


        public static void SerializeToXml(WiseLinkConfiguration config)
        {
            TextWriter tw = new StreamWriter(_configFilePath, false);
            XmlSerializer xr = new XmlSerializer(typeof(WiseLinkConfiguration));
            xr.Serialize(tw, config);
            tw.Close();
        }

        public static WiseLinkConfiguration DeSerializeToObject()
        {
            if (_myConfiguration == null && File.Exists(_configFilePath))
            {

                FileStream fs = new FileStream(_configFilePath, FileMode.Open);
                XmlSerializer xr = new XmlSerializer(typeof(WiseLinkConfiguration));
                _myConfiguration = (WiseLinkConfiguration)xr.Deserialize(fs);
                fs.Close();

            }
            if (_myConfiguration == null)
            {
                throw new ArgumentException(string.Format("Can't deserialize configure file: path={0}", _configFilePath));
            }
            else
            {
                return _myConfiguration;
            }
        }
        public static string GetConfigValueFromAppConfig(AppConfigFileName fileName, string nodeName)
        {
            AppConfig myConfig = (fileName == AppConfigFileName.CCF) ? _ccfConfig : _zicConfig;

            AppConfigFileNode configNode = GetAppConfigFileNode(fileName, nodeName);

            return myConfig.GetValue(nodeName,configNode.SectionName,configNode.AttributeName);

        }

        public static void SetConfigValueToAppConfig(AppConfigFileName fileName, string nodeName,string nodeValue)
        {
            AppConfig myConfig = (fileName == AppConfigFileName.CCF) ? _ccfConfig : _zicConfig;

            AppConfigFileNode configNode = GetAppConfigFileNode(fileName, nodeName);
            myConfig.SetValue(nodeName, configNode.SectionName,configNode.AttributeName,nodeValue);
            myConfig.SaveConfigDoc();

        }

        public static AppConfigFileNode GetAppConfigFileNode(AppConfigFileName fileName, string nodeName)
        {
            Tuple<AppConfigFileName, string> tkey = Tuple.Create<AppConfigFileName, string>(fileName, nodeName);
            return ConfigFileNodeList[tkey];
        }
        public static void CheckDBConnection()
        {

            WiseLinkConfiguration myConfig = MyConfiguration;
            
            try
            {
                ProfileModel.SaveZICUrl(myConfig.zicurl, myConfig.isjava);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Open"))
                {
                    LoggerHelper.LogCCF20("车务通无法连接数据库，请检查系统配置!");
                    LoggerHelper.LogCCF20(ex.Message);
                    Utility.ShowMessageBox("车务通无法连接数据库，请检查系统配置!");

                }
                else
                {
                    throw ex;
                }
            }
        }
    }
}
